#include <system/Mutex.h>

namespace ne
{
    Mutex::Mutex()
        : mpMutex(0),
          mIsLocked(false)
    {
        mpMutex = new MutexID();
        pthread_mutex_init(mpMutex, 0);
    }

    bool Mutex::isLocked() const
    {
        return mIsLocked;
    }

    bool Mutex::lock()
    {
        if (isLocked()) return false;

        if (pthread_mutex_lock(mpMutex) > 0)
        {
            return false;
        }

        mIsLocked = true;
        return true;
    }

    bool Mutex::trylock()
    {
        if (isLocked()) return false;

        if (pthread_mutex_trylock(mpMutex) > 0)
        {
            return false;
        }

        mIsLocked = true;
        return true;
    }

    bool Mutex::unlock()
    {
        if (!isLocked()) return false;

        if (pthread_mutex_unlock(mpMutex) > 0)
        {
            return false;
        }

        mIsLocked = false;
        return true;
    }

    Mutex::~Mutex()
    {
        unlock();
        pthread_mutex_destroy(mpMutex);
        delete mpMutex;
    }
}
